1 /*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.cache;
18
19 import com.google.common.annotations.Beta;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.ImmutableMap;
22
23 import java.util.concurrent.ExecutionException;
24
25 /**
26 * A cache which forwards all its method calls to another cache. Subclasses should override one or
27 * more methods to modify the behavior of the backing cache as desired per the
28 * <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
29 *
30 * <p>Note that {@link #get}, {@link #getUnchecked}, and {@link #apply} all expose the same
31 * underlying functionality, so should probably be overridden as a group.
32 *
33 * @author Charles Fry
34 * @since 11.0
35 */
36 @Beta
37 public abstract class ForwardingLoadingCache<K, V>
38 extends ForwardingCache<K, V> implements LoadingCache<K, V> {
39
40 /** Constructor for use by subclasses. */
41 protected ForwardingLoadingCache() {}
42
43 @Override
44 protected abstract LoadingCache<K, V> delegate();
45
46 @Override
47 public V get(K key) throws ExecutionException {
48 return delegate().get(key);
49 }
50
51 @Override
52 public V getUnchecked(K key) {
53 return delegate().getUnchecked(key);
54 }
55
56 @Override
57 public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
58 return delegate().getAll(keys);
59 }
60
61 @Override
62 public V apply(K key) {
63 return delegate().apply(key);
64 }
65
66 @Override
67 public void refresh(K key) {
68 delegate().refresh(key);
69 }
70
71 /**
72 * A simplified version of {@link ForwardingLoadingCache} where subclasses can pass in an already
73 * constructed {@link LoadingCache} as the delegete.
74 *
75 * @since 10.0
76 */
77 @Beta
78 public abstract static class SimpleForwardingLoadingCache<K, V>
79 extends ForwardingLoadingCache<K, V> {
80 private final LoadingCache<K, V> delegate;
81
82 protected SimpleForwardingLoadingCache(LoadingCache<K, V> delegate) {
83 this.delegate = Preconditions.checkNotNull(delegate);
84 }
85
86 @Override
87 protected final LoadingCache<K, V> delegate() {
88 return delegate;
89 }
90 }
91 }